<template>
  <el-dialog
    :title="basicForm.id ? '编辑课程' : '创建课程'"
    :class="[$store.state.appPrefix + '-c-add-course-dialog', 'g-dialog']"
    width="448px"
    :show-close="!isLoading"
    :close-on-click-modal="false"
    :visible.sync="dialogVisible"
    :loading="isLoading">
    <el-form
      class="is-comfortable"
      label-position="left"
      v-loading="isLoading"
      label-width="140px"
      ref="basicForm"
      :rules="rules"
      :model="basicForm">
      <el-form-item label="课程名称" prop="courseName" class="is-required">
        <el-input
          v-model="basicForm.courseName"
          size="small"
          clearable
          show-word-limit
          placeholder="请输入课程名称">
        </el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button :disabled="isLoading" @click="dialogVisible = false">取 消</el-button>
      <el-button :disabled="isLoading" type="primary" @click="$debounceSave">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
/* global _ */
import checkForm from 'mixins/checkform'
import { addCourse } from './models'
import { validateCourseName } from 'utils/ui-utils'

export default {
  mixins: [
    checkForm
  ],
  props: {
    dialogVisible: {
      type: Boolean,
      required: true
    },
    formData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      isLoading: false,
      basicForm: {
        id: null,
        courseName: ''
      },
      rules: {
        courseName: [
          { required: true, message: '请输入课程名称', trigger: 'blur' },
          { validator: validateCourseName, trigger: 'blur' }
        ]
      },
      debounceSave: null
    }
  },
  watch: {
    dialogVisible(val) {
      this.$emit('update:dialogVisible', val)
      this.basicForm.courseName = ''
    }
  },
  methods: {
    $debounceSave() {
      if (!this.debounceSave) {
        this.debounceSave = _.debounce(this.$handleSave, 500)
      }
      this.debounceSave()
    },
    async $handleSave() {
      this.isLoading = true
      if (!this.$checkForm('basicForm')) {
        this.isLoading = false
        return
      }
      const params = {
        ...this.basicForm
      }
      try {
        const { data } = await addCourse(params)
        if (data) {
          this.$message.success('保存成功')
        }
        this.$emit('saveSucc', { id: data }, () => {
          this.isLoading = false
        })
      } catch (err) {
        this.isLoading = false
        this.$message.error(err.message || err.message || '保存信息出错')
      }
    }
  }
}
</script>
